import 'package:flutter/material.dart';

class DashedBorderText extends StatelessWidget {
  final String text;
  final double dashWidth;
  final double dashSpace;
  final double borderWidth;
  final Color color;

  const DashedBorderText({
    super.key,
    required this.text,
    this.dashWidth = 1,
    this.dashSpace = 1,
    this.borderWidth = 1,
    this.color = Colors.blue,
  });

  @override
  Widget build(BuildContext context) {
    return CustomPaint(
      painter: DashedBorderPainter(
        dashWidth: dashWidth,
        dashSpace: dashSpace,
        borderWidth: borderWidth,
        color: color,
      ),
      child: Padding(
        padding: const EdgeInsets.all(2.0),
        child: Text(
          text,
          style: TextStyle(color: color),
        ),
      ),
    );
  }
}

class DashedBorderPainter extends CustomPainter {
  final double dashWidth;
  final double dashSpace;
  final double borderWidth;
  final Color color;

  DashedBorderPainter({
    required this.dashWidth,
    required this.dashSpace,
    required this.borderWidth,
    required this.color,
  });

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = color
      ..strokeWidth = borderWidth
      ..style = PaintingStyle.stroke;

    final totalLength = dashWidth + dashSpace;
    final horizontalDashCount = (size.width / totalLength).floor();
    final verticalDashCount = (size.height / totalLength).floor();

    // 绘制顶部边框
    for (int i = 0; i < horizontalDashCount; i++) {
      final startX = i * totalLength;
      canvas.drawLine(
        Offset(startX, 0),
        Offset(startX + dashWidth, 0),
        paint,
      );
    }

    // 绘制右侧边框
    for (int i = 0; i < verticalDashCount; i++) {
      final startY = i * totalLength;
      canvas.drawLine(
        Offset(size.width, startY),
        Offset(size.width, startY + dashWidth),
        paint,
      );
    }

    // 绘制底部边框
    for (int i = 0; i < horizontalDashCount; i++) {
      final startX = i * totalLength;
      canvas.drawLine(
        Offset(startX, size.height),
        Offset(startX + dashWidth, size.height),
        paint,
      );
    }

    // 绘制左侧边框
    for (int i = 0; i < verticalDashCount; i++) {
      final startY = i * totalLength;
      canvas.drawLine(
        Offset(0, startY),
        Offset(0, startY + dashWidth),
        paint,
      );
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return false;
  }
}

// 使用示例
// void main() {
//   runApp(
//     MaterialApp(
//       home: Scaffold(
//         appBar: AppBar(title: const Text('Dashed Border Text')),
//         body: Center(
//           child: DashedBorderText(
//             text: '被虚线边框包裹的文本',
//           ),
//         ),
//       ),
//     ),
//   );
// }